package org.xdq.demo.user.api;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.xdq.demo.base.*;
import org.xdq.demo.user.dto.UserDto;
import org.xdq.demo.user.service.UserService;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/")
    public Result addUser(@RequestBody UserDto userDto){
        try{
            userService.addUser(userDto);
            return Result.OK();
        }catch(BusinessException e){
            return Result.err(Result.CODE_ERR_BUSINESS, e.getMessage());
        }catch(SysException e){
            log.error("系统错误！", e);//输出错误日志
            return Result.err(Result.CODE_ERR_SYS, "系统升级中....");
        }

    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto){
        try{
            CurrentUser currentUser = userService.checkLogin(userDto);

            /*
                将当前用户信息生成一个经过加密的令牌，发送到客户端
             */

            Object token = TokenUtils.loginSign(currentUser,userDto.getU_pwd());

            return Result.OK(token);

        }catch(BusinessException e){
            return Result.err(Result.CODE_ERR_BUSINESS, e.getMessage());
        }catch(SysException e){
            log.error("系统错误！", e);//输出错误日志
            return Result.err(Result.CODE_ERR_SYS, "系统升级中....");
        }

    }
}
